package com.wml.sellPhone.service.impl;

import com.wml.sellPhone.dao.UserMapper;
import com.wml.sellPhone.pojo.User;
import com.wml.sellPhone.service.IUserService;
import com.wml.sellPhone.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录实现类
 *
 * @author Hayes
 * @date 2018-06-27 13:08
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录服务
     *
     * @param name 用户名
     * @param password 用户密码
     * @param request
     * @return
     */
    @Override
    public boolean login(String name, String password, HttpServletRequest request) {
        // 根据userCode 调用 userMapper 中的方法，获取用户
        User user = userMapper.selectByUserName(name);
        // 根据 user 信息， 判断用户是否登录成功
        // 如果登陆成功
        if (user != null && user.getPassword().equals(password)) {
            // 把用户的信息传入Session中
            request.getSession().setAttribute(Constant.USER_INFO, user);
            return true;
        }
        return false;
    }


    /**
     * 注册用户
      * @param user 传递的user对象
     * @return
     */
    @Override
    public boolean register(User user) {
        int insert = userMapper.insert(user);
        return insert > 0;
    }


    /**
     * 更新密码
     *
     * @param password
     * @param request
     */
    @Override
    public void updatePassword(String password, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Constant.RESETUSER);
        Long userId = user.getUserid();
        // 更新用户的密码
        userMapper.updatePassword(password, userId);
        // 更新后删除属性
        request.getSession().removeAttribute(Constant.RESETUSER);
    }

    /**
     * 判断用户是否存在
     * @param userName
     * @return
     */
    @Override
    public boolean existUserName(String userName) {
        User user = userMapper.selectByUserName(userName);
        return user != null;
    }

    /**
     * 注册时判断邮箱是否存在
     * @param email
     * @return
     */
    @Override
    public boolean existEmail(String email) {
        User user = userMapper.selectByEmail(email);
        return user != null;
    }
}
